package com.qire.manhua.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;

import com.qire.other.thirdPlatform.WeChatPlatform;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import androidx.fragment.app.FragmentActivity;

public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler {

	private static WeChatShareCallback weChatShareCallback;

	public static void setShareCallback(WeChatShareCallback weChatShareCallback) {
		WXEntryActivity.weChatShareCallback = weChatShareCallback;
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            Intent intent = getIntent();
			WeChatPlatform.WeChat.weChatApi().handleIntent(intent, this);
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		WeChatPlatform.WeChat.weChatApi().handleIntent(intent, this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		weChatShareCallback = null;
	}

	@Override
	public void onReq(BaseReq req) {

	}

	@Override
	public void onResp(BaseResp resp) {

		if(resp instanceof SendAuth.Resp) {
			SendAuth.Resp sendAuthResp = (SendAuth.Resp) resp;

			Bundle data = new Bundle();
			data.putInt("ErrCode", sendAuthResp.errCode);
			data.putString("code", sendAuthResp.code);
			data.putString("state", sendAuthResp.state);
			data.putString("lang", sendAuthResp.lang);
			data.putString("country", sendAuthResp.country);

			Message msg = Message.obtain();
			msg.what = WeChatPlatform.Authorization;
			msg.setData(data);
			WeChatPlatform.WeChat.sendMessage(msg);
		} else if(resp instanceof SendMessageToWX.Resp) {
			SendMessageToWX.Resp sendMessageResp = (SendMessageToWX.Resp) resp;
			switch (resp.errCode) {
				case BaseResp.ErrCode.ERR_OK:
					// 分享成功
				case BaseResp.ErrCode.ERR_USER_CANCEL:
					// 已取消操作
				case BaseResp.ErrCode.ERR_AUTH_DENIED:
					// 发送被拒绝
				case BaseResp.ErrCode.ERR_UNSUPPORT:
					// 不支持错误
					onShareCallback();
					break;
				default:
					// 发送返回
					break;
			}
		}

        finish();
	}

	private void onShareCallback() {
		if(weChatShareCallback != null) {
			weChatShareCallback.onCall();
		}
	}

	public interface WeChatShareCallback {
		void onCall();
	}
}